package com.devnn.view;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.devnn.base.R;
import com.devnn.base.BaseProject;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DecimalFormat;

public class DownLoadDialog extends Dialog implements View.OnClickListener, Runnable, Handler.Callback {
    private Button btnOK;
    private TextView tvMessage;
    private Context context;
    private String url;
    private Handler handler;
    private ProgressBar pBar;
    private OnDownLoadProgressChangedListener onDownloadListener;

    public interface OnDownLoadProgressChangedListener {
        public void onDownLoadFinished();
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setOnDownloadListener(
            OnDownLoadProgressChangedListener onDownloadListener) {
        this.onDownloadListener = onDownloadListener;
    }

    public DownLoadDialog(Context context) {
        super(context);
        this.context = context;
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        handler = new Handler(this);
        // TODO Auto-generated constructor stub
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.view_progress);
        getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        this.getWindow().setLayout(context.getResources().getDisplayMetrics().widthPixels - 40, LayoutParams.WRAP_CONTENT);
        initView();
        setEvent();
    }

    public void startDownLoad(String url) {
        this.url = url;
        Thread thread = new Thread(this);
        thread.start();
    }

    private void initView() {
        tvMessage = (TextView) findViewById(R.id.pro_tip);
        btnOK = (Button) findViewById(R.id.pro_ok);
        pBar = (ProgressBar) findViewById(R.id.pro_bar);

    }

    private void setEvent() {
        btnOK.setOnClickListener(this);
    }

    public void setMessage(String msg) {
        tvMessage.setText(msg);
    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        if (v.equals(this.btnOK)) {
            this.dismiss();
        }

    }

    @Override
    public void run() {
        // TODO Auto-generated method stub
        HttpClient client = new DefaultHttpClient();
        HttpGet get = new HttpGet(url);
        HttpResponse response;
        try {
            response = client.execute(get);
            HttpEntity entity = response.getEntity();
            long length = entity.getContentLength();
            Log.i("download", "文件长度:" + length);
            Message msg = handler.obtainMessage();
            msg.arg1 = (int) length;
            msg.what = 200;
            handler.sendMessage(msg);
            InputStream is = entity.getContent();
            FileOutputStream fileOutputStream = null;
            if (is != null) {
                File file = new File(BaseProject.APK_PATH);
                if (!file.exists()) {
                    file.getParentFile().mkdirs();
                }
                fileOutputStream = new FileOutputStream(file);
                byte[] buf = new byte[1024];
                int ch = -1;
                int count = 0;
                while ((ch = is.read(buf)) != -1) {
                    fileOutputStream.write(buf, 0, ch);
                    count += ch;
                    msg = handler.obtainMessage();
                    msg.arg1 = count;
                    msg.what = 300;
                    handler.sendMessage(msg);
                    if (length > 0) {
                    }
                }
                fileOutputStream.flush();
                if (fileOutputStream != null) {
                    fileOutputStream.close();
                }
            }
            handler.sendEmptyMessage(100);//完成
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private DecimalFormat format = new DecimalFormat("00");

    @Override
    public boolean handleMessage(Message msg) {
        // TODO Auto-generated method stub
        if (msg.what == 100) {
            Log.i("download", "finished");
            update();
            this.dismiss();
        } else if (msg.what == 200) {//设最大长度
            pBar.setMax(msg.arg1);
        } else if (msg.what == 300) {//更新进度
            Log.i("download", msg.arg1 + "");
            this.tvMessage.setText("正在下载：" + format.format(100 * (float) pBar.getProgress() / pBar.getMax()) + "%");
            pBar.setProgress(msg.arg1);
        }
        return false;
    }

    private void update() {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setDataAndType(Uri.fromFile(new File(BaseProject.APK_PATH)),
                "application/vnd.android.package-archive");
        context.startActivity(intent);
    }
}
